package com.shadow.demo.data.mapping.reader;

import com.shadow.demo.data.mapping.common.DataConfigNode;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;


import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Component
public class DataMappingReader extends BaseReader<DataConfigNode<Map<String, Object>>> {

    private static final String FILE_PATH = "classpath:config/data.json";
    private final ResourceLoader resourceLoader;

    public DataMappingReader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    public void init() {
        refreshCache();
    }

    /**
     * 获取缓存内容.
     * */
    @Override
    public DataConfigNode<Map<String, Object>> getJsonContent() {
        if (isFileUpdated()) {
            refreshCache();
        }
        return cachedJsonContent;
    }

    public void refreshCache() {
        try {
            Resource resource = resourceLoader.getResource(FILE_PATH);
            File file = resource.getFile();
            String content = new String(FileCopyUtils.copyToByteArray(file), StandardCharsets.UTF_8);
            parse(content);
            cachedJsonResource = resource;
            lastModified = resource.lastModified();
            log.info("refreshCache success");
        } catch (IOException e) {
            log.error("refreshCache error", e);
        }
    }

    private void parse(final String content) {
//        try {
//            DataConfigNode dataConfigNode = JacksonUtils.toObject(content, DataConfigNode.class);
//            super.cachedJsonContent = dataConfigNode;
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
    }
}
